package cn.edu.lingnan.controller;


import cn.edu.lingnan.domain.Dto.UserLoginDto;
import cn.edu.lingnan.domain.Dto.UserRegisterDto;
import cn.edu.lingnan.domain.Vo.UserVo;
import cn.edu.lingnan.domain.pojo.User;
import cn.edu.lingnan.service.UserService;
import cn.edu.lingnan.service.impl.UserServiceImpl;
import cn.edu.lingnan.utils.EmailUtil;
import cn.edu.lingnan.utils.JwtUtils;
import cn.hutool.core.bean.BeanUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping
@RequiredArgsConstructor
@Slf4j
public class LoginAndRegisterController {



    private final UserService userService;

    private final RedisTemplate redisTemplate;


    @PostMapping("/login")
    public Result login(@RequestBody UserLoginDto userLoginDto, HttpServletRequest request) {

        log.info("登录信息：{}", userLoginDto);
         // 获取当前会话的 sessionId
        String sessionId = request.getSession().getId();

        // 从 Redis 中获取存储的验证码
        String storedCaptcha = (String) redisTemplate.opsForValue().get("captcha:" + sessionId);

        // 验证验证码（忽略大小写）
        if (  userLoginDto.getCaptcha() == null || !  userLoginDto.getCaptcha().equalsIgnoreCase(storedCaptcha)) {
            return Result.error("验证码错误或已过期，请重新输入！");
        }

        // 验证通过后，删除 Redis 中的验证码，防止重复使用
        redisTemplate.delete("captcha:" + sessionId);
         User user=  userService.login(userLoginDto);

         if(user == null){
             return Result.error("用户名或密码错误或用户不存在！");
         }

         if(user.getStatus() == 0){
             return Result.error("用户已被禁用，请联系管理员！");

         }

        // 登陆成功，生成 JWT token
        String jwt = JwtUtils.generateJwt(Map.of(
                "id", user.getUserId(),
                "username", user.getAccount()
        ));

        // 构建 UserLoginVO
        UserVo userVO =  UserVo.builder()
                .userId( user.getUserId())
                .roleId(user.getRoleId())
                .email(user.getEmail())
                .createTime(user.getCreateTime())
                .userName(user.getUserName())
                .updateTime(user.getUpdateTime())
                .avatar(user.getAvatar())
                .permissions(user.getPermissions())
                .role(user.getRoleId() == 1? "teacher" : "student")
                .token(jwt)
                .build();

        return Result.success( userVO);

    }

    //发送邮箱验证码
//发送邮箱验证码
    @GetMapping("/common/sendEmailCaptcha")
    public Result sendEmailCaptcha(@RequestParam("email") String email, HttpServletRequest request) {
        log.info("发送邮箱验证码：{}", email);
        // 获取当前会话的 sessionId
        String sessionId = request.getSession().getId();

        // 异步执行验证码发送
        new Thread(() -> EmailUtil.sendCaptcha(email, sessionId)).start();

        // 立即返回成功响应
        return Result.success("验证码发送成功，请注意查收！");
    }


    @PostMapping("/register")
    public Result register(@RequestBody UserRegisterDto userRegisterDto, HttpServletRequest request) {
        log.info("注册信息：{}",userRegisterDto);
        String sessionId = request.getSession().getId();

     Integer result =    userService.register(userRegisterDto,sessionId);
     if(result==-1){
         return Result.error("验证码错误或已过期，请重新输入！");
     }
     return Result.success("注册成功！");
    }

}
